﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IRIS.Models;
using System.Net.Mail;
using System.Configuration;

namespace IRIS.Controllers
{
    public class ContactController : Controller
    {
         public ActionResult Index() {
            var model = new ContactFormModel();
            return View(model);
        }

        // This funciton will take information out from the contact form and send it with email with the SmtpClient. 
        // Username and password in the global Web.Config file
        
        [HttpPost]
        [ValidateInput(false)] 
        public ActionResult Index(ContactFormModel theData) 
        {
            if (string.IsNullOrEmpty(theData.Nafn))
            ModelState.AddModelError("Nafn", "Nafn verður að fylgja með.");
            if (string.IsNullOrEmpty(theData.Email))
            ModelState.AddModelError("Email", "Email verður að fylgja með.");
            if (theData.Fyrirspurn == "<br>")
            ModelState.AddModelError("Fyrirspurn", "Innihald má ekki vanta");

           try 
           {
                if (ModelState.IsValid) 
                {
                    using (MailMessage message = new MailMessage())
                    {
                        //From System.Configuration Library
                        string strEmail = ConfigurationManager.AppSettings["EmailAdress"]; 
                        //Add to the email form  
                        message.To.Add(strEmail);
                        message.Subject = theData.Nafn;
                        message.Body= DateTime.Today.ToShortDateString() + "  -  " + theData.Email + " \n \n" + theData.Fyrirspurn;                            
                           
                        SmtpClient client = new SmtpClient();
                        client.EnableSsl = true; 
                        client.Send(message);                                              
                    }
                    return RedirectToAction("Success");
                } 
                else
                {
                    return View(theData);
                }
           }
           catch (Exception) 
           {
               return View("Error");
           }         
        }
        public ViewResult Success() 
        {
            return View();
        }
    }
}
